package com.yonyou.pmclouds.plan.processor;

import com.yonyou.pmclouds.basecom.billstatus.BillStatusConst;
import com.yonyou.pmclouds.basecom.bp.processor.SingleProcessor;
import com.yonyou.pmclouds.basecom.consts.BillTypeConst;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.plan.entity.ScheduleVO;
import com.yonyou.pmclouds.plan.rmiitf.IScheduleQueryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.UUID;

/**
 *
 * @Description: 计划编制保存前处理类
 * @Author: zhangzhonghao
 * @Date: 2020-03-06
 */

@Component
public class ScheduleInsertBeforeProcessor implements SingleProcessor<ScheduleVO> {

    @Autowired
    private IScheduleQueryService scheduleQueryService;

    @Override
    public void process(ScheduleVO vo, ScheduleVO orig) throws BusinessException {

        checkValue(vo);

        setDefault(vo);

    }

    private void checkValue(ScheduleVO vo) throws BusinessException {

        if(StringUtils.isEmpty(vo.getName())){
            throw new BusinessException("计划名称不允许为空！");
        }

        if(StringUtils.isBlank(vo.getPkProject())){
            throw new BusinessException("项目不能为空！");
        }
    }

    private void setDefault(ScheduleVO vo) throws BusinessException {
        String pkSchedule = UUID.randomUUID().toString();
        vo.setVersion(1);
        vo.setLastFlag("Y");
        vo.setPkSchedule(pkSchedule);
        vo.setPkOriginal(pkSchedule);
        vo.setPkTenant(RuntimeEnvironment.getTenantId());
        vo.setBillstatus(BillStatusConst.COMMON_FREE_STATUS);
        vo.setBillType(BillTypeConst.PROCESS_PLAN_BILLTYPE);
        vo.setCreator(RuntimeEnvironment.getLoginUserId());
        vo.setCreationtime(Calendar.getInstance().getTime());
        vo.setSeq(getSeq(vo.getPkProject()));
    }

    private int getSeq(String pkProject) throws BusinessException {
        return scheduleQueryService.queryCountByPkProject(pkProject);
    }
}
